<template>
  <div class="article-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>文章管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd">发布文章</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="搜索关键词" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="标题/作者"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 文章列表 -->
      <el-table
        v-loading="loading"
        :data="articleList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="title" label="文章标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column prop="likeCount" label="点赞数" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="success"
              @click="handlePreview(row)"
            >
              预览
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑文章对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发布文章' : '编辑文章'"
      width="1000px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-upload
            class="cover-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="cover" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章摘要" prop="summary">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入文章摘要"
          />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor-container">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="15"
              placeholder="请输入文章内容"
            />
          </div>
        </el-form-item>
        <el-form-item label="文章标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">立即发布</el-radio>
            <el-radio :label="0">保存草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="文章预览"
      width="800px"
    >
      <div class="article-preview">
        <h1 class="article-title">{{ preview.title }}</h1>
        <div class="article-meta">
          <span>作者：{{ preview.author }}</span>
          <span>发布时间：{{ preview.publishTime }}</span>
          <span>分类：{{ preview.categoryName }}</span>
        </div>
        <div class="article-content" v-html="preview.content"></div>
        <div class="article-tags">
          <el-tag
            v-for="tag in preview.tags"
            :key="tag.id"
            class="tag-item"
          >
            {{ tag.name }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getArticleList,
  getArticleDetail,
  addArticle,
  updateArticle,
  deleteArticle,
  getCategoryList,
  getTagList
} from '@/api/content'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  categoryId: undefined,
  status: undefined,
  timeRange: [],
  keyword: ''
})

// 状态选项
const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '已发布', value: 1 },
  { label: '已下线', value: 2 }
]

// 分类选项
const categoryOptions = ref([])
// 标签选项
const tagOptions = ref([])

// 上传地址
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'

// 表格数据
const loading = ref(false)
const articleList = ref([])
const total = ref(0)

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  title: '',
  categoryId: undefined,
  author: '',
  coverImage: '',
  summary: '',
  content: '',
  tags: [],
  status: 1
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 预览对话框
const previewDialogVisible = ref(false)
const preview = ref({})

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const item = statusOptions.find(item => item.value === status)
  return item ? item.label : status
}

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await getCategoryList()
    categoryOptions.value = res.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取标签列表
const getTags = async () => {
  try {
    const res = await getTagList()
    tagOptions.value = res.data
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getArticleList(queryParams.value)
    articleList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取文章列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    status: undefined,
    timeRange: [],
    keyword: ''
  }
  handleQuery()
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    title: '',
    categoryId: undefined,
    author: '',
    coverImage: '',
    summary: '',
    content: '',
    tags: [],
    status: 1
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = async (row) => {
  try {
    const res = await getArticleDetail(row.id)
    dialogType.value = 'edit'
    form.value = {
      id: row.id,
      ...res.data
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addArticle(form.value)
          ElMessage.success('发布成功')
        } else {
          await updateArticle(form.value)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '发布失败:' : '编辑失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '发布失败' : '编辑失败')
      }
    }
  })
}

// 预览按钮点击
const handlePreview = async (row) => {
  try {
    const res = await getArticleDetail(row.id)
    preview.value = res.data
    previewDialogVisible.value = true
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  }
}

// 删除按钮点击
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该文章吗？', '提示', {
      type: 'warning'
    })
    
    await deleteArticle(row.id)
    ElMessage.success('删除成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.coverImage = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

onMounted(() => {
  getCategories()
  getTags()
  handleQuery()
})
</script>

<style lang="scss" scoped>
.article-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .cover-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }
  
  .cover {
    width: 200px;
    height: 120px;
    display: block;
    object-fit: cover;
  }
  
  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
  
  .article-preview {
    padding: 20px;
    
    .article-title {
      font-size: 24px;
      font-weight: bold;
      text-align: center;
      margin-bottom: 20px;
    }
    
    .article-meta {
      text-align: center;
      color: #909399;
      margin-bottom: 20px;
      
      span {
        margin: 0 10px;
      }
    }
    
    .article-content {
      line-height: 1.8;
      margin-bottom: 20px;
    }
    
    .article-tags {
      .tag-item {
        margin-right: 10px;
      }
    }
  }
}
</style> 